package com.campus.food.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * Web配置类
 * 
 * @author Claude3.7 Sonnet
 * @since 2025-05-29
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {
    
    @Autowired
    private FileUploadConfig fileUploadConfig;
    
    /**
     * 配置跨域
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .allowCredentials(true)
                .maxAge(3600);
    }
    
    /**
     * 配置静态资源处理
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 配置Swagger UI资源
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
        
        // 配置上传文件访问路径
        String uploadPath = "file:" + fileUploadConfig.getBasePath() + "/";
        
        // 配置各类型文件访问路径
        registry.addResourceHandler("/api/file/merchant/**")
                .addResourceLocations("file:" + fileUploadConfig.getMerchantUploadPath() + "/");
        
        registry.addResourceHandler("/api/file/food/**")
                .addResourceLocations("file:" + fileUploadConfig.getFoodUploadPath() + "/");
        
        registry.addResourceHandler("/api/file/avatar/**")
                .addResourceLocations("file:" + fileUploadConfig.getAvatarUploadPath() + "/");
        
        registry.addResourceHandler("/api/file/review/**")
                .addResourceLocations("file:" + fileUploadConfig.getReviewUploadPath() + "/");
        
        registry.addResourceHandler("/api/file/common/**")
                .addResourceLocations("file:" + fileUploadConfig.getBasePath() + "/common/");
        
        registry.addResourceHandler("/uploads/**")
                .addResourceLocations(uploadPath);
    }
} 